package concurrency_queue

import (
	"channel/cond"
	"channel/queue"
	"channel/ring_buffer"
	"context"
	"sync"
)

type SliceQueue[T any] struct {
	queue    ring_buffer.Ring
	notFull  *cond.Cond
	notEmpty *cond.Cond
	mu       *sync.Mutex
}

func (b *SliceQueue[T]) Enqueue(ctx context.Context, t T) error {
	if ctx.Err() != nil {
		return ctx.Err()
	}
	b.mu.Lock()
	if ctx.Err() != nil {
		return ctx.Err()
	}
	defer b.mu.Unlock()
	for b.queue.IsFull() {
		err := b.notFull.WaitV2(ctx)
		if err != nil {
			return err
		}
	}
	err := b.queue.Write(ctx, t)
	if err != nil {
		return err
	}
	if b.queue.IsFull() {
		b.notEmpty.Broadcast()
	}
	return nil
}

func (b *SliceQueue[T]) Dequeue(ctx context.Context) (T, error) {
	if ctx.Err() != nil {
		var t T
		return t, ctx.Err()
	}
	b.mu.Lock()
	if ctx.Err() != nil {
		var t T
		return t, ctx.Err()
	}
	defer b.mu.Unlock()
	for b.queue.IsEmpty() {
		err := b.notEmpty.WaitV2(ctx)
		if err != nil {
			var t T
			return t, err
		}
	}
	t, err := b.queue.Read()
	if err != nil {
		return t, err
	}
	b.notFull.Broadcast()
	return t.(T), nil
}

func NewSliceQueue[T any](size int) queue.Queue[T] {
	mu := &sync.Mutex{}
	return &SliceQueue[T]{
		queue:    ring_buffer.NewRingBuffer(size),
		notFull:  cond.NewCond(mu),
		notEmpty: cond.NewCond(mu),
		mu:       mu,
	}
}

func NewSliceQueueV2[T any](size int) *SliceQueue[T] {
	mu := &sync.Mutex{}
	return &SliceQueue[T]{
		queue:    ring_buffer.NewRingBuffer(size),
		notFull:  cond.NewCond(mu),
		notEmpty: cond.NewCond(mu),
		mu:       mu,
	}
}

var _ queue.Queue[int] = (*SliceQueue[int])(nil)
